﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using System.IO;
using Facade.Excel;

namespace PeisongWeb.admin
{
    public partial class systemPriceModulus : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("CF", 1))
                {
                    ddlBusinessNature();
                    rootCategoryBind();
                    priceStructureBind();
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("您没有权限操作!", "index.aspx");
                    return;
                }
            }
        }

        private void ddlBusinessNature()
        {
            DataTable dt = logic.sysCode.buyerNatureList();
            ddl_businessNature.DataSource = dt;
            ddl_businessNature.DataBind();
            ddl_businessNature.SelectedIndex = 1;
            ddl_BN.DataSource = dt;
            ddl_BN.DataBind();
            ddl_BN.SelectedIndex = 1;
        }
        private void rootCategoryBind()
        {
            DataTable dt = logic.category.getByParent(0);
            drp_parent.DataSource = dt;
            drp_parent.DataBind();
            drp_parent.Items.Insert(0, new ListItem("-请选择大类-", "-1"));

            ddlRootCategory.DataSource = dt;
            ddlRootCategory.DataBind();
            ddlRootCategory.Items.Insert(0, new ListItem("-请选择大类-", "-1"));
        }

        private void subCategoryBind(int parentId)
        {
            DataTable dt = logic.category.getByParent(parentId);
            ddlSubCategory.DataSource = dt;
            ddlSubCategory.DataBind();
            ddlSubCategory.Items.Insert(0, new ListItem("-请选择小类-", "-1"));
        }

        protected void ddlRootCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlRootCategory.SelectedValue != "-1")
            {
                subCategoryBind(Convert.ToInt32(ddlRootCategory.SelectedValue));
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        private string selectBywhere()
        {
           string bn = ddl_BN.SelectedValue;
           StringBuilder where = new StringBuilder();
           where.Append("1=1");
           if (bn != "-1")
           {
               where.AppendFormat(" and businessNature={0}", bn);
               if (ddlRootCategory.SelectedValue != "-1" && !string.IsNullOrEmpty(ddlRootCategory.SelectedValue))
                   where.AppendFormat(" and parentCategoryId={0}", ddlRootCategory.SelectedValue);
               if (ddlSubCategory.SelectedValue != "-1" && !string.IsNullOrEmpty(ddlSubCategory.SelectedValue))
                   where.AppendFormat(" and categoryId={0}", ddlSubCategory.SelectedValue);
               if (!string.IsNullOrEmpty(txtProductName.Text))
                   where.AppendFormat(" and productName like '%{0}%'", txtProductName.Text);
               if (!string.IsNullOrEmpty(txtProductNo.Text))
                   where.AppendFormat(" and productNo='{0}'", txtProductNo.Text);
           }
           return where.ToString();
        }

        private void rptBind()
        {
            string bn = ddl_BN.SelectedValue;
            if (bn != "-1")
            {
                DataSet ds = logic.priceStructure.listWithProductAutoAdd(selectBywhere(), "productId", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
                AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                ViewState["dtCount"] = ds.Tables[0].Rows[0][0];
                rpt_list.DataSource = ds.Tables[1];
                rpt_list.DataBind();
            }
        }
        // 按商品设置系统加价导出Excel
        protected void lbn_ImportByProduct_Click(object sender, EventArgs e)
        {
            string s = selectBywhere();
            DataTable dt = logic.priceStructure.listWithProductAutoAdd(selectBywhere(), "categoryid asc,productId asc",Convert.ToInt32(ViewState["dtCount"]),1).Tables[1];
            StringBuilder title = new StringBuilder();
            title.Append(ddl_BN.SelectedItem.Text.Trim() + "档次");
            if (ddlRootCategory.SelectedValue != "-1" && !string.IsNullOrEmpty(ddlRootCategory.SelectedValue))
                title.Append("["+ddlRootCategory.SelectedItem.Text.Trim());
            if (ddlSubCategory.SelectedValue != "-1" && !string.IsNullOrEmpty(ddlSubCategory.SelectedValue))
                title.Append("-"+ddlSubCategory.SelectedItem.Text.Trim()+"]");
            title.Append("系统加价体系");


            // 导出Excel
            ExportFacade exportInstance = new Facade.Excel.ExportFacade();

            DataTable newDt = dt.DefaultView.ToTable(true, new string[2] { "parentCategoryId", "parentCategoryName" });
            Dictionary<string, string> sheetList = new Dictionary<string, string>();
            for (int i = 0; i < newDt.Rows.Count; i++)
            {
                sheetList.Add(newDt.Rows[i][0].ToString(), newDt.Rows[i][1].ToString());
            }

            Dictionary<string, string> columns = new Dictionary<string, string>();
            columns.Add("categroyName", "小类");
            columns.Add("productNo", "商品编号");
            columns.Add("productName", "商品名称");
            columns.Add("productAutoAdd", "系统加价体系");

            Dictionary<int, FormatStyle> formatOptions = new Dictionary<int, FormatStyle>();

            exportInstance.ExportByWeb("parentCategoryId={0}", sheetList, columns, dt, title.ToString(), title.ToString() + ".xls", formatOptions, "商品系统加价体系");

        }

        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                int productId = 0;
                int.TryParse(e.CommandArgument.ToString(), out productId);

                decimal autoAddNew = Convert.ToDecimal(hdCurrentNewAutoAdd.Value);
                decimal autoAddOld = Convert.ToDecimal(hdCurrentOldAutoAdd.Value);

                if (autoAddNew != autoAddOld)
                {
                    logic.product.productUpdateAutoAdd(logic.sysAdmin.AdminID, productId, autoAddNew);
                    logic.priceStructure.updateByProductIdAndBN(ddl_businessNature.SelectedValue, productId, autoAddNew, logic.sysAdmin.AdminID);
                    ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), "提示", "alert('保存成功！');", true);
                    rptBind();
                }
            }
        }

        private void priceStructureBind()
        {
            if (ddl_businessNature.SelectedValue!="-1")
            {
                DataTable dt = logic.sysPriceModulus.listByBusinessNature(ddl_businessNature.SelectedValue, Convert.ToInt32(drp_parent.SelectedValue));
                rptPriceStructure.DataSource = dt;
                rptPriceStructure.DataBind(); 
            }

        }

        protected void linkSearch_Click(object sender, EventArgs e)
        {
            priceStructureBind();
        }

        protected void lnkSelect_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void btn_PriceStructureSave_Click(object sender, EventArgs e)
        {
            string categoryAutoPercentMap = hd_pricePercent.Value;
            logic.sysPriceModulus.updateByBusinessNature(ddl_businessNature.SelectedValue, categoryAutoPercentMap,logic.sysAdmin.AdminID);
            Library.Script.ClientMsg("系统价格体系设置成功!");
            priceStructureBind();
        }

        protected void lbn_Import_Click(object sender, EventArgs e)
        {
            DataTable dt = logic.sysPriceModulus.listByBusinessNature(ddl_businessNature.SelectedValue, Convert.ToInt32(drp_parent.SelectedValue));
            dt.Columns.Remove("categoryid");//删除列   
            dt.Columns.Remove("parentid"); //删除列 
            dt.Columns["parentCategory"].ColumnName = "大类";
            dt.Columns["category"].ColumnName = "小类";
            dt.Columns["sysAutoAdd"].ColumnName = "系统加价体系";

            string title = ddl_businessNature.SelectedItem.Text.Trim() + "档次的系统加价体系";

            ExportFacade exportInstance = new Facade.Excel.ExportFacade();
            Dictionary<int, FormatStyle> formatOptions = new Dictionary<int, FormatStyle>();
            exportInstance.ExportByWeb(dt, title, title + ".xls", formatOptions, title);
        }
    }
}
